import React, { useState } from "react";
import axios from "axios";
import { createParser } from "eventsource-parser";

function App() {
  const [prompt, setPrompt] = useState("写1000字关于AI的文章");
  const [response, setResponse] = useState("");
  const [loading, setLoading] = useState(false);

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setPrompt(e.target.value);
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    setResponse("");

    try {
      const responseStream = await fetch(
        "http://localhost:8001/api/v1/chat_vllm/stream/",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            model: "vllm",
            messages: [{ role: "user", content: prompt }],
          }),
        }
      );

      if (!responseStream.body) {
        throw new Error("ReadableStream not supported in this browser.");
      }

      console.log(responseStream);
      // 创建一个读取器来处理流式响应
      const reader = responseStream.body.getReader();
      const decoder = new TextDecoder("utf-8");

      while (true) {
        const { done, value } = await reader.read();
        console.log(done);
        console.log(value);
        if (done) break;
        const chunk = decoder.decode(value, { stream: true });
        console.log(chunk);

        // 假设服务器返回的数据格式是 "data: <chunk>\n\n"
        const lines = chunk.split("\n\n");
        // .filter((line) => line.startsWith("data: "));
        lines.forEach((line) => {
          // const data = line.slice(6); // 去掉 'data: ' 前缀
          const data = line.replace("data: ", "");
          try {
            setResponse((prev) => prev + data);
          } catch (e) {
            console.error("Failed to parse SSE data:", e);
          }
        });
      }

      setLoading(false);
    } catch (error) {
      console.error("Failed to fetch the response:", error);
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: "20px" }}>
      <h1>Chat with vLLM</h1>
      <form onSubmit={handleSubmit}>
        <textarea
          rows={4}
          cols={50}
          value={prompt}
          onChange={handleInputChange}
          placeholder="Type your message here..."
        />
        <br />
        <button type="submit" disabled={loading}>
          {loading ? "Generating..." : "Send"}
        </button>
      </form>
      <div
        style={{
          marginTop: "20px",
          border: "1px solid #ccc",
          padding: "10px",
          minHeight: "100px",
        }}
      >
        <p>{response}</p>
      </div>
    </div>
  );
}

export default App;
